package com.sinosoft.common.util;
/**
 * 
 * @author unhappydepig 
 * @mail yqw8912@163.com
 * @time 2015-4-27 下午5:46:46
 */
public class StringUtil {
	/**
	 * 替换字符串
	 * @param str
	 * @param searchStr
	 * @param replaceStr
	 * @return
	 */
	public static String replace(String str, String searchStr, String replaceStr) {
	    int i = 0;
	    int j = 0;
	    if (str == null) {
	      return null;
	    }
	    if ("".equals(str)) {
	      return "";
	    }
	    if ((searchStr == null) || (searchStr.equals(""))) {
	      return str;
	    }
	    String newReplaceStr = replaceStr;
	    if (replaceStr == null) {
	      newReplaceStr = "";
	    }
	    StringBuilder buffer = new StringBuilder();
	    while ((j = indexOf(str, searchStr, i, 0)) > -1) {
	      buffer.append(str.substring(i, j));
	      buffer.append(newReplaceStr);
	      i = j + searchStr.length();
	    }
	    buffer.append(str.substring(i, str.length()));
	    return buffer.toString();
	}
	/**
	 * indexof
	 * @param str
	 * @param subStr
	 * @param startIndex
	 * @param occurrenceTimes
	 * @return
	 */
	 public static int indexOf(String str, String subStr, int startIndex, int occurrenceTimes)
	  {
	    int foundCount = 0;
	    int index = startIndex;
	    if (occurrenceTimes <= 0) {
	      return -1;
	    }
	    if (str.length() - 1 < startIndex) {
	      return -1;
	    }
	    if ("".equals(subStr)) {
	      return 0;
	    }
	    int substrLength = subStr.length();
	    while (foundCount < occurrenceTimes) {
	      index = str.indexOf(subStr, index);
	      if (index == -1) {
	        return -1;
	      }
	      foundCount++;
	      index += substrLength;
	    }
	    return index - substrLength;
	  }	

		/**
		 * 按字符拆分字符串
		 * 
		 * @param originalString
		 * @param delimiterString
		 * @return
		 */
		public static String[] split(String originalString, String delimiterString) {
			int index = 0;
			String[] returnArray = null;
			int length = 0;

			if ((originalString == null) || (delimiterString == null)
					|| ("".equals(originalString))) {
				return new String[0];
			}

			if (("".equals(originalString)) || ("".equals(delimiterString))
					|| (originalString.length() < delimiterString.length())) {
				return new String[] { originalString };
			}

			String strTemp = originalString;
			while ((strTemp != null) && (!strTemp.equals(""))) {
				index = strTemp.indexOf(delimiterString);
				if (index == -1) {
					break;
				}
				length++;
				strTemp = strTemp.substring(index + delimiterString.length());
			}
			length++;
			returnArray = new String[length];

			strTemp = originalString;
			for (int i = 0; i < length - 1; i++) {
				index = strTemp.indexOf(delimiterString);
				returnArray[i] = strTemp.substring(0, index);
				strTemp = strTemp.substring(index + delimiterString.length());
			}
			returnArray[(length - 1)] = strTemp;
			return returnArray;
		}	 
}
